package com.diapoc.diorsgallery.utils;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.diapoc.diorsgallery.R;

public abstract class MyBaseAdapter extends BaseAdapter {
	private MyViewHolder viewHolder;
	private LayoutInflater mInflater;
	private Context context;
	private int count;
	private static Context auxiliaryContext;

	public MyBaseAdapter(MyViewHolder viewHolder, Context context) {
		this.viewHolder = viewHolder;
		this.context = context;
		this.auxiliaryContext = context;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return count;
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final int finalPosition = position;
		MyViewHolder tempViewHolder = null;
		if (convertView == null) {
			convertView = mInflater.inflate(viewHolder.layoutId, parent);
			for (int i = 0; i < viewHolder.views.size(); i++) {
				tempViewHolder = new MyViewHolder(viewHolder.layoutId);
				tempViewHolder.addView();
				HashMap<Integer, Object> tag = (HashMap<Integer, Object>) viewHolder.views
						.get(i).getTag();
				View newView = convertView.findViewById((Integer) tag
						.get(MyViewHolder.TAG_ID));
				newView.setTag((Integer) tag.get(MyViewHolder.TAG_TYPE));
				newView.setId((Integer) tag.get(MyViewHolder.TAG_TYPE));
				tempViewHolder.views.set(i, newView);
			}
			convertView.setTag(tempViewHolder);
		} else {
			tempViewHolder = (MyViewHolder) convertView.getTag();
		}
		oppView(finalPosition, tempViewHolder);
		return convertView;

	}

	public void setCount(int count) {
		this.count = count;
	}

	abstract public void oppView(int finalPosition, MyViewHolder tempViewHolder);

	public static class MyViewHolder {
		public final static int TYPE_TEXTVIEW = 0x0001;
		public final static int TYPE_IMAGEVIEW = 0x0002;
		/**
		 * view的标签位置：类型
		 */
		private final static int TAG_TYPE = R.id.TAG_TYPE;
		/**
		 * view的标签位置：layoutId
		 */
		private final static int TAG_ID = R.id.TAG_ID;

		public ArrayList<View> views = null;
		public int layoutId;

		public MyViewHolder(int layoutId) {
			views = new ArrayList<View>();
			this.layoutId = layoutId;
		}

		public void addView(int type, int id) {
			View view = new View(auxiliaryContext);
			HashMap<Integer, Object> hm = new HashMap<Integer, Object>();
			hm.put(TAG_TYPE, type);
			hm.put(TAG_ID, id);
			view.setTag(hm);
			views.add(view);
		}

		public void addView() {
			View view = new View(auxiliaryContext);
			views.add(view);
		}
	};
}
